/* 类似 asynckit 库，传入任务数组，并行运行任务，其中一个出错返回错误原因 */
/* 但此题要求实现 promise.All() */

// 需要理解 js 的 promise 原理，与并行编程的经验

// ## 使用 async-await
let promiseAll1 = async function(functions) {
  return new Promise((resolve, reject) => {
    if (functions.length === 0) {
      resolve([]);
      return;
    }

    const res = new Array(functions.length).fill(null);

    let resolvedCnt = 0;

    functions.forEach(async (el, idx) => {
      try {
        const subResult = await el();
        res[ idx ] = subResult;
        resolvedCnt++;
        if (resolvedCnt == functions.length) {
          resolve(res);
        }
      } catch (error) {
        reject(error);
      }
    });
  });
};

// ## then-catch

var promiseAll2 = function(functions) {
  return new Promise((resolve,reject) => {
      if(functions.length === 0) {
          resolve([])
          return
      }

      const res = new Array(functions.length).fill(null)

      let resolvedCount = 0

      functions.forEach((el,idx) => {
          el().then((subResult) => {
              res[idx] = subResult
              resolvedCount++
              if(resolvedCount === functions.length) {
                  resolve(res)
              }
          }).catch((err) => {
              reject(err)
          })
      })
  })
};

